export default {
  data () {
    return {
      rolesData: [],
      // 角色授权对话框打开状态
      rolesFormVisible: false,
      powerData: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      roleId: -1
    }
  },
  created () {
    // 获取角色列表
    this.loadRolesList()
    // 获取权限列表
    this.loadRightsList()
  },
  methods: {
    // 返回从 0 开始的索引
    indexMethod (index) {
      return index
    },
    async loadRolesList () {
      // 获取角色列表
      try {
        const res = await this.$axios.get('roles')
        // console.log(res)
        this.rolesData = res.data.data
      } catch (error) {
        console.log('获取角色列表失败')
      }
    },
    // 获取权限列表
    async loadRightsList () {
      const res = await this.$axios.get('rights/tree')
      this.powerData = res.data.data
    },
    // 打开角色授权对话框, 获取选中节点的key所组成的数组
    openPowerDialog (row) {
      this.rolesFormVisible = true
      this.roleId = row.id
      const powerKeys = []
      row.children.forEach(item1 => {
        item1.children.forEach(item2 => {
          item2.children.forEach(item3 => {
            powerKeys.push(item3.id)
          })
        })
      })
      //  this.$nextTick() 在DOM更新后调用里面的回调函数
      // this.$refs.powerTree.setCheckedKeys() 设置树形控件里面节点的选中状态
      this.$nextTick(() => {
        this.$refs.powerTree.setCheckedKeys(powerKeys)
      })
    },
    // 确认修改权限
    async confirmImpower () {
      const key1 = this.$refs.powerTree.getCheckedKeys() // 获取全选的key值
      const key2 = this.$refs.powerTree.getHalfCheckedKeys() // 获取半选的key值
      const key = [...key1, ...key2]
      // console.log(this.roleId, key)
      await this.$axios.post(`roles/${this.roleId}/rights`, {
        rids: key.join(',')
      })
      this.rolesFormVisible = false
      this.loadRolesList()
      this.$message({
        type: 'success',
        message: '更新成功'
      })
    }
  }
}
